import { useRoutes, useLocation, useNavigate, Navigate } from "react-router-dom"
import { useEffect } from "react"
const UseRouteWithGuard = (key, routes) => {
    let token = localStorage.getItem(key)
    let location = useLocation()
    let navigate = useNavigate()
    let Element = useRoutes(routes)
    useEffect(() => {    //hook钩子里不能使用条件语句，所以要把条件语句放到钩子里面
        if (!token) {
            if (location.pathname !== "/login") {
                navigate("/login")
            }
        }
    }, [])
    //通过useMemo处理，解决闪烁的问题
    //闪烁的问题，以为组件更新，每次都返回一个新的路由配置，需要重写加载，导致闪烁的问题
    //使用useMemo来缓存路由配置
    return Element
}
export default UseRouteWithGuard